//
//  TaxesCalculatorViewController.m
//  Rong360
//
//  Created by tianliwei on 8/2/14.
//  Copyright (c) 2014 tianliwei. All rights reserved.
//

#import "TaxesCalculatorViewController.h"
#import "TaxesResultViewController.h"
#import "TaxesHistoryViewController.h"
#import "NewHouseCell.h"
#import "TaxesCalculator.h"
#import "TaxesSecondHandView.h"

#define mjFieldTag 0
#define zjFieldTag 1
#define yjFieldTag 2
#define jzfsBtnTag 3
#define fclxBtnTag 4
#define gfnfBtnTag 5
#define scgfBtnTag 6
#define wyzfBtnTag 7

@interface TaxesCalculatorViewController ()
@property (nonatomic, strong) CalculatePanelView *calculateView;
@property (nonatomic, strong) NSArray *titles;
@property (nonatomic, strong) NSArray *subTitles;
@property (nonatomic, strong) UITextField *currentField;
@property (nonatomic, strong) UISegmentedControl *segmentedControl;
@property (nonatomic, assign) BOOL bBegin;
//二手
@property (nonatomic, strong) TaxesSecondHandView *secondHandView;
@property (nonatomic, strong) NSArray *jzfsTitles;
@property (nonatomic, strong) NSArray *fclxTitles;
@property (nonatomic, strong) NSArray *otherTitles;

@property (nonatomic, strong) TaxesCalculator *taxesCal;

@end

static NSString *CellIdentifier = @"Cell";

@implementation TaxesCalculatorViewController

- (id)init
{
    self = [super init];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)history{
    self.hidesBottomBarWhenPushed = YES;
    TaxesHistoryViewController *taxesHistoryVC = [[TaxesHistoryViewController alloc]initWithHousehandType:self.taxesCal.houseHandType];
    [self.navigationController pushViewController:taxesHistoryVC animated:YES];
}

- (void)calculate{
    if (self.taxesCal.houseHandType == HouseSecondHand) {
        switch (self.currentField.tag) {
            case 0:
                self.taxesCal.square_second = self.currentField.text;
                break;
            case 1:
                self.taxesCal.totalPrice_second = self.currentField.text;
                break;
            case 2:
                self.taxesCal.orginPrice = self.currentField.text;
                break;
            default:
                break;
        }
    }else if (self.taxesCal.houseHandType == HouseNew){
        switch (self.currentField.tag) {
            case 0:
                self.taxesCal.totalPrice_new = self.currentField.text;
                break;
            case 1:
                self.taxesCal.square_new = self.currentField.text;
                break;
            default:
                break;
        }
    }
    if (0) {//今后再写
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"对不起，请将选项填写完整" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
    }else{
        if (self.taxesCal.houseHandType == HouseSecondHand) {
            [self.taxesCal beginCalculateWithHouseSecondHand];
            
        }else if (self.taxesCal.houseHandType == HouseNew){
            [self.taxesCal beginCalculateWithHouseNew];
        }
        self.hidesBottomBarWhenPushed = YES;
        TaxesResultViewController *taxesResultVC = [[TaxesResultViewController alloc]initWithTaxesCal:self.taxesCal];
        [self.navigationController pushViewController:taxesResultVC animated:YES];
    }
}
- (void)initSegmentControl{
    
    NSArray *segmentedArray = [[NSArray alloc]initWithObjects:@"二手房",@"新房",nil];
    
    //初始化UISegmentedControl
    
    self.segmentedControl = [[UISegmentedControl alloc]initWithItems:segmentedArray];
    
    self.segmentedControl.frame = CGRectMake(10.0, 10.0, 300.0, 35.0);
    
    self.segmentedControl.selectedSegmentIndex = 0;//设置默认选择项索引
    
    self.taxesCal.houseHandType = HouseSecondHand;
    
    self.segmentedControl.tintColor = RGBCOLOR(0, 172, 238);
    
    //有基本四种样式
    self.segmentedControl.segmentedControlStyle = UISegmentedControlStylePlain;//设置样式
    
    [self.segmentedControl addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];  //添加委托方法
    [self.view addSubview:self.segmentedControl];
}



//具体委托方法实例

-(void)segmentAction:(UISegmentedControl *)Seg{
    [self.currentField resignFirstResponder];
    NSInteger Index = Seg.selectedSegmentIndex;
    switch (Index) {
        case 0:
            self.tableView.hidden = YES;
            self.secondHandView.hidden = NO;
            self.taxesCal.houseHandType = HouseSecondHand;
            break;
        case 1:
            
            self.tableView.hidden = NO;
            self.secondHandView.hidden = YES;
            self.taxesCal.houseHandType = HouseNew;
            break;
        default:
            break;
    }
}

- (void)initSecondHandView{
    self.secondHandView = [[[NSBundle mainBundle]loadNibNamed:@"TaxesSecondHandView" owner:self options:nil]lastObject];
    [self.view addSubview:self.secondHandView];
    [self.secondHandView setY:60];
    [self.secondHandView setH:IS_IPHONE_5 ? 240 : 170];
    
    for (UIView *v in self.secondHandView.subviews) {
        if ([v isKindOfClass:[UITextField class]]) {
            UITextField *textField = (UITextField *)v;
            textField.delegate = self;
            textField.inputView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 1, 1)];
        }else if ([v isKindOfClass:[UIButton class]]) {
            UIButton *button = (UIButton *)v;
            [button addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
        }
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    self.jzfsTitles = @[@"总价", @"差价"];
    self.fclxTitles = @[@"普通住宅", @"非普通住宅", @"经适房"];
    self.otherTitles = @[@"是", @"否"];
    self.view.backgroundColor = [UIColor whiteColor];
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 50, UI_SCREEN_WIDTH, 300)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    NSInteger rowHeight = IS_IPHONE_5 ? 56 : 40;
    self.tableView.rowHeight = rowHeight;
    self.tableView.scrollEnabled = NO;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.hidden = YES;
    [self.tableView registerNib:[UINib nibWithNibName:@"NewHouseCell" bundle:nil] forCellReuseIdentifier:CellIdentifier];
    [self.view addSubview:self.tableView];
    
    self.title = @"税费计算器";
    self.titles = @[@"房屋总价",@"房屋总面积"];
    self.subTitles = @[@"万元",@"平米"];
         
    self.calculateView = [[[NSBundle mainBundle]loadNibNamed:@"CalculatePanelView" owner:self options:NULL]lastObject];
    self.calculateView.Y = UI_NAVIFRAME_HEIGHT-180;
    self.calculateView.delegate = self;
    [self.view addSubview:self.calculateView];
    [self initSegmentControl];
    [self initSecondHandView];
    
    self.taxesCal = [[TaxesCalculator alloc]init];
    self.taxesCal.firstBuy = YES;
    self.taxesCal.overFive = YES;
    self.taxesCal.onlyOne = YES;
    //房屋原值（跟计征方式联动，当计征方式为“总价”时置灰不可点，当为“差价”时点亮可点）
    if (self.taxesCal.markType == TotalType) {
        [self.secondHandView setOriginPriceEnable:NO];
    }
    
    UIButton *historyButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [historyButton setBackgroundColor:[UIColor clearColor]];
    [historyButton setTitle:@"历史" forState:UIControlStateNormal];
    [historyButton addTarget:self action:@selector(history) forControlEvents:UIControlEventTouchUpInside];
    historyButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    historyButton.frame = CGRectMake(0.0f, 0.0f, 40.0f, 25.0f);
    UIBarButtonItem *historyButtonItem = [[UIBarButtonItem alloc] initWithCustomView:historyButton];
    self.navigationItem.rightBarButtonItem = historyButtonItem;
 
}


- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    switch (actionSheet.tag) {
        case jzfsBtnTag:{
            if (buttonIndex == 2) {
                return;
            }
            NSString *str = self.jzfsTitles[buttonIndex];
            self.secondHandView.payType.text = str;
            self.taxesCal.markType = buttonIndex;
            if (self.taxesCal.markType == TotalType) {
                [self.secondHandView setOriginPriceEnable:NO];
            }else if (self.taxesCal.markType == DiffType){
                [self.secondHandView setOriginPriceEnable:YES];
            }
            break;
        }
        case fclxBtnTag:{
            if (buttonIndex == 3) {
                return;
            }
            NSString *str = self.fclxTitles[buttonIndex];
            self.secondHandView.houseType.text = str;
            self.taxesCal.houseType = buttonIndex;
            break;
        }
        case gfnfBtnTag:{
            if (buttonIndex == 2) {
                return;
            }
            NSString *str = self.otherTitles[buttonIndex];
            self.secondHandView.overFive.text = str;
            if (buttonIndex == 0) {
                self.taxesCal.overFive = YES;
            }else if (buttonIndex == 1){
                self.taxesCal.overFive = NO;
            }
            break;
        }
        case scgfBtnTag:{
            if (buttonIndex == 2) {
                return;
            }
            NSString *str = self.otherTitles[buttonIndex];
            self.secondHandView.firstBuy.text = str;
            if (buttonIndex == 0) {
                self.taxesCal.firstBuy = YES;
            }else if (buttonIndex == 1){
                self.taxesCal.firstBuy = NO;
            }
            break;
        }
        case wyzfBtnTag:{
            if (buttonIndex == 2) {
                return;
            }
            NSString *str = self.otherTitles[buttonIndex];
            self.secondHandView.onlyOne.text = str;
            if (buttonIndex == 0) {
                self.taxesCal.onlyOne = YES;
            }else if (buttonIndex == 1){
                self.taxesCal.onlyOne = NO;
            }
            break;
        }
        default:
            break;
    }
    
//    NSIndexPath *path = [NSIndexPath indexPathForRow:4 inSection:0];
//    NSArray *paths = [NSArray arrayWithObject:path];
//    [self.tableView reloadRowsAtIndexPaths:paths withRowAnimation:UITableViewRowAnimationAutomatic];
}

- (void)btnClicked:(UIButton *)sender{
    switch (sender.tag) {
        case jzfsBtnTag:{
            UIActionSheet *actionSheet = [[UIActionSheet alloc]initWithTitle:@"计征方式" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"总价", @"差价", nil];
            actionSheet.tag = sender.tag;
            [actionSheet showInView:self.view];
            break;
        }
        case fclxBtnTag:{
            UIActionSheet *actionSheet = [[UIActionSheet alloc]initWithTitle:@"房产类型" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"普通住宅", @"非普通住宅", @"经适房", nil];
            actionSheet.tag = sender.tag;
            [actionSheet showInView:self.view];
            break;
        }
        case gfnfBtnTag:{
            UIActionSheet *actionSheet = [[UIActionSheet alloc]initWithTitle:@"购房满5年" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"是", @"否", nil];
            actionSheet.tag = sender.tag;
            [actionSheet showInView:self.view];
            break;
        }
        case scgfBtnTag:{
            UIActionSheet *actionSheet = [[UIActionSheet alloc]initWithTitle:@"买方首次购房" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"是", @"否", nil];
            actionSheet.tag = sender.tag;
            [actionSheet showInView:self.view];
            break;
        }
        case wyzfBtnTag:{
            UIActionSheet *actionSheet = [[UIActionSheet alloc]initWithTitle:@"卖方唯一住房" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"是", @"否", nil];
            actionSheet.tag = sender.tag;
            [actionSheet showInView:self.view];
            break;
        }
        default:
            break;
    }
}

- (void)keyBtnClicked:(UIButton *)sender{
    NSString *currentStr = self.currentField.text;
    switch (sender.tag) {
        case 0:
        case 1:
        case 2:
        case 3:
        case 4:
        case 5:
        case 6:
        case 7:
        case 8:
        case 9:
            [self inputNumber:sender.titleLabel.text];
            break;
        case 10:{//"."
            BOOL notDot = ([self.currentField.text rangeOfString:@"."].location == NSNotFound);
            if(notDot){
                currentStr= [currentStr stringByAppendingString:@"."];
                self.currentField.text= currentStr;
            }
            break;
        }
        case 11:{//"C"
            self.currentField.text = @"";
            self.bBegin = YES;
            break;
        }
            
        case 12:{
            [self calculate];
            break;
        }
        default:
            break;
    }
}

- (void)inputNumber:(NSString *)str
{
    if([self.currentField.text isEqualToString:@"0"] && [str isEqualToString:@"0"]){
        return;
    }
    if(self.bBegin){
        self.currentField.text= str;
    }else{
        self.currentField.text= [self.currentField.text stringByAppendingString:str];
    }
    self.bBegin= NO;
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{
    if (self.taxesCal.houseHandType == HouseSecondHand) {
        switch (textField.tag) {
            case 0:
                self.taxesCal.square_second = textField.text;
                break;
            case 1:
                self.taxesCal.totalPrice_second = textField.text;
                break;
            case 2:
                self.taxesCal.orginPrice = textField.text;
                break;
                
            default:
                break;
        }
    }else if (self.taxesCal.houseHandType == HouseNew){
        switch (textField.tag) {
            case 0:
                self.taxesCal.totalPrice_new = textField.text;
                break;
            case 1:
                self.taxesCal.square_new = textField.text;
            default:
                break;
        }
        [textField setUserInteractionEnabled:NO];
    }
    return YES;
}

-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    self.currentField = textField;
    return YES;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return self.titles.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NewHouseCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    cell.mainLabel.text = self.titles[indexPath.row];
    cell.unitLabel.text = self.subTitles[indexPath.row];
    cell.textField.delegate = self;
    cell.textField.inputView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 1, 1)];
    cell.textField.tag = indexPath.row;
    [cell.textField setUserInteractionEnabled:NO];
    // Configure the cell...
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NewHouseCell *cell = (NewHouseCell *)[tableView cellForRowAtIndexPath:indexPath];
    [cell.textField setUserInteractionEnabled:YES];
    [cell.textField becomeFirstResponder];
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a story board-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}

 */

@end
